package com.laomo.lib_bt.ota;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.le.ScanResult;
import android.content.Context;
import android.util.Log;

import com.jieli.jl_bt_ota.BuildConfig;
import com.jieli.jl_bt_ota.constant.BluetoothConstant;
import com.jieli.jl_bt_ota.constant.StateCode;
import com.jieli.jl_bt_ota.impl.BluetoothOTAManager;
import com.jieli.jl_bt_ota.interfaces.BtEventCallback;
import com.jieli.jl_bt_ota.model.BluetoothOTAConfigure;
import com.jieli.jl_bt_ota.model.response.TargetInfoResponse;
import com.jieli.jl_bt_ota.tool.DeviceStatusManager;
import com.jieli.jl_bt_ota.util.CommonUtil;
import com.jieli.jl_bt_ota.util.JL_Log;
import com.laomo.lib_bt.BleManager;


/**
 * 类说明：
 *
 * @author laomo
 * @date 2024/8/13 15:35
 */
public class OTAManager extends BluetoothOTAManager {


    public OTAManager(Context context) {
        super(context);
        init();
    }

    private void init() {
        JL_Log.setLog(false);
        //JL_Log.setLog(true);
        BluetoothOTAConfigure bluetoothOption = BluetoothOTAConfigure.createDefault();
        //选择通讯方式
        bluetoothOption.setPriority(BluetoothOTAConfigure.PREFER_BLE);
        //是否需要自定义回连方式(默认不需要，如需要自定义回连方式，需要客户自行实现)
        bluetoothOption.setUseReconnect(false/*(PreferencesHelper.getSharedPreferences(mContext)
                .getBoolean(
                        JLConstant.KEY_USE_CUSTOM_RECONNECT_WAY,
                        JLConstant.NEED_CUSTOM_RECONNECT_WAY
                ) && PreferencesHelper.getSharedPreferences(mContext)
                .getBoolean(JLConstant.KEY_IS_HID_DEVICE, JLConstant.HID_DEVICE_WAY))*/);
        //是否启用设备认证流程(与固件工程师确认)
        bluetoothOption.setUseAuthDevice(true/*PreferencesHelper.getSharedPreferences(mContext)
                .getBoolean(JLConstant.KEY_IS_USE_DEVICE_AUTH, JLConstant.IS_NEED_DEVICE_AUTH)*/);
        //设置BLE的MTU
        bluetoothOption.setMtu(BluetoothConstant.BLE_MTU_MIN);//
        //是否需要改变BLE的MTU
        bluetoothOption.setNeedChangeMtu(false);
        //是否启用杰理服务器(暂时不支持)
        bluetoothOption.setUseJLServer(false);
//        bleManager.setBleMtu(20);
        //配置OTA参数
        configure(bluetoothOption);
        //LogUtil.d("==配置OTA参数=" + bluetoothOption.toString() + " bleManager.connectedBtDevice:" + bleManager.getConnectedDevices());


        registerBluetoothCallback(new BtEventCallback() {
            @Override
            public void onConnection(BluetoothDevice device, int status) {
                super.onConnection(device, status);
                //LogUtil.d("=== BtEventCallback onConnection status:" + status);
                if (status == StateCode.CONNECTION_OK) { //准备完成
                    Log.d(TAG, "ota准备完成");
                    //获取设备信息的两种方式
                    //第一种方式是直接调用缓存设备信息，判断是否需要强制升级，判断mandatoryUpgradeFlag是否等于1即可
                    TargetInfoResponse info = DeviceStatusManager.getInstance().getDeviceInfo(device);
                    if (info != null) {
                        if (isOTA()) {

                        } else {
                            OTAUtil.getInstance(CommonUtil.getMainContext()).onOtaAvailable(device,info.isMandatoryUpgrade());
                        }
                    }
                }
            }
        });
    }


    @Override
    public BluetoothDevice getConnectedDevice() {
        BluetoothGatt latestConnectedBtGatt = getConnectedBluetoothGatt();
        if (latestConnectedBtGatt != null) {
            return latestConnectedBtGatt.getDevice();
        }
        return null;
    }

    @Override
    public BluetoothGatt getConnectedBluetoothGatt() {
        return BleManager.getInstance(CommonUtil.getMainContext()).getLatestConnectedBtGatt();
    }

    @Override
    public void connectBluetoothDevice(BluetoothDevice bluetoothDevice) {
        BleManager.getInstance(CommonUtil.getMainContext()).connect(bluetoothDevice);
    }

    @Override
    public void disconnectBluetoothDevice(BluetoothDevice bluetoothDevice) {

    }

    @Override
    public boolean sendDataToDevice(BluetoothDevice bluetoothDevice, byte[] bytes) {
        //JL_Log.d(TAG, "sendDataToDevice "+new Gson().toJson(bytes));
        OTAUtil.getInstance(CommonUtil.getMainContext()).writeDataByBleAsync(bluetoothDevice,
                BluetoothConstant.UUID_SERVICE,
                BluetoothConstant.UUID_WRITE,
                bytes, (device, serviceUUID, characteristicUUID, result, data) -> {
                    //JL_Log.i(TAG, "-writeDataByBleAsync- result = " + result + ", device:" + BluetoothUtil.printBtDeviceInfo(device) + ", data:" + CHexConver.byte2HexStr(data));
                });
        return true;
    }
}
